/*
 * @Author: yanjikun
 * @Date: 2022-01-12 10:30:21
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-03-23 16:36:03
 * @Description: file content
 */

import { isNullOrUndef, isObject, isString, isArray, isFunction } from '@/utils/is'
import { ComputedRef, unref } from 'vue'
import { FormConfig } from '../types/form'
import { BasicProps } from '../props'
import { set } from 'lodash'
import { dateUtil } from '@/utils/dateUtil'

interface UseFormValuesContext {
  formConfigRef: ComputedRef<FormConfig[]>
  formModel: Recordable
  getFormProps: ComputedRef<BasicProps>
  defaultFormValues: Recordable
}
export const useFormValues = ({
  formConfigRef,
  formModel,
  getFormProps,
  defaultFormValues
}: UseFormValuesContext) => {
  const handleFormValues = (values: Recordable) => {
    if (!isObject(values)) {
      return {}
    }
    const res: Recordable = {}
    for (const item of Object.entries(values)) {
      let [, value] = item
      const [key] = item
      if (!key || (isArray(value) && value.length === 0) || isFunction(value)) {
        continue
      }
      const transformDateFunc = unref(getFormProps).transformDateFunc
      if (isObject(value)) {
        value = transformDateFunc?.(value)
      }
      if (isArray(value) && value[0]?.format && value[1]?.format) {
        value = value.map((item) => transformDateFunc?.(item))
      }
      if (isString(value)) {
        value?.trim()
      }
      set(res, key, value)
    }

    return handleRangeTimeValue(res)
  }
  const handleRangeTimeValue = (values: Recordable) => {
    const fieldMapToTime = unref(getFormProps).fieldMapToTime
    if (!fieldMapToTime || !isArray(fieldMapToTime)) {
      return values
    }
    for (const [field, [startTimeKey, endTimeKey], format = 'YYYY-MM-DD'] of fieldMapToTime) {
      if (!field || !startTimeKey || !endTimeKey || !values[field]) {
        continue
      }
      const [startTime, endTime]: string[] = values[field]
      values[startTimeKey] = dateUtil(startTime).format(format)
      values[endTimeKey] = dateUtil(endTime).format(format)
      Reflect.deleteProperty(values, field)
    }
    return values
  }
  const initDefault = () => {
    const configs = unref(formConfigRef)
    configs.forEach((item) => {
      const { field, defaultValue } = item
      if (!isNullOrUndef(defaultValue)) {
        formModel[field] = defaultValue
        defaultFormValues[field] = defaultValue
      }
    })
  }
  return { handleFormValues, initDefault }
}
